//
//  JPhotoBrowserVC.swift
//  JMicroBlog
//
//  Created by Jason on 24/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit
import SVProgressHUD
// MARK: - 照片浏览的控制器 
private let reuseId = "JPhotoBrowserCell"
// 主要提供的照片浏览查看的功能
class JPhotoBrowserVC: UIViewController,UICollectionViewDataSource{

    // 提供一个NSURL数组用于接收大图数组
    var imgURLs:[NSURL]?
    
    // 设置照片索引
    var index:Int = 0 {
        didSet {
            
        }
    }
    
    // 布局懒加载
    lazy var layout : UICollectionViewFlowLayout = {
        let l = UICollectionViewFlowLayout()
        
        // 设置layout的布局属性
        l.itemSize = self.view.bounds.size
        l.minimumInteritemSpacing = 0
        l.minimumLineSpacing = 0
        // 水平滚动
        l.scrollDirection = UICollectionViewScrollDirection.Horizontal
        return l
    }()
    
    lazy var closeBtn : UIButton = {
        return self.createBtn("关闭")
    }()
    
    lazy var saveBtn : UIButton = {
        return self.createBtn("保存")
    }()
    
    // 纯代码开发在这里需要一个colleciton的变量 同样懒加载
    lazy var collectionView : UICollectionView = {
        let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.layout)
        // 成为数据源代理
        cv.dataSource = self
        // 隐藏水平滚动条
        cv.showsHorizontalScrollIndicator = false
        // 设置可分页
        cv.pagingEnabled = true
        // 取消弹簧属性
        cv.bounces = false
        return cv
    }()
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        scrollIndex()
    }
//    override func viewWillAppear(animated: Bool) {
//        super.viewWillAppear(animated)
//        
//    }
    
    // 滚动到指定的索引
    private func scrollIndex() {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    // MARK: - 需要注意的方法
    // 纯代码开发需要实现这个方法,这个方法与xib,storyboard的相同,但优先级最高
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.addSubview(collectionView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册可重用cell的类
        collectionView.registerClass(JPhotoBrowserCell.self, forCellWithReuseIdentifier: reuseId)
//        
//        let closeBtn = createBtn("关闭")
//        let saveBtn = createBtn("保存")
//        
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        // 1 > VFL
        var con = [AnyObject]()
        // 将生成的数据添加到数组中
        con += NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[closeBtn(80)]-8-[saveBtn(80)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn":closeBtn,"saveBtn":saveBtn])
        
        con += NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn":closeBtn])
        
        con.append(NSLayoutConstraint(item: saveBtn, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: closeBtn, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        
        // 添加约束
        view.addConstraints(con)
    }
    
    // 重构 
    private func createBtn(btnName:String,pView:UIView? = nil) -> UIButton {
        let btn = UIButton()
        btn.setTitle(btnName,forState:UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.brownColor()
        btn.setTranslatesAutoresizingMaskIntoConstraints(false)
        // 创建控件最终都是需要显示的,所以默认添加到当前控制器对应的view中
        if pView == nil {
            view.addSubview(btn)
        } else {
            pView?.addSubview(btn)
        }
        return btn
    }
    
    func close() {
        closeBtn.hidden = true
        saveBtn.hidden = true
        dismissViewControllerAnimated(true, completion: nil)
    }
    func save() {
        let image = (collectionView.visibleCells().last as! JPhotoBrowserCell).viewerVC?.imgView.image
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
        if error != nil {
            JLog.i("错误")
            return
        }
//        JLog.i("写入成功")
        SVProgressHUD.showInfoWithStatus("写入成功")
    }
    
    //MARK: - UICollectionView的数据源代理
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! JPhotoBrowserCell
        // cell.backgroundColor = UIColor(red: rndColor(), green: rndColor(), blue: rndColor(), alpha: 1.0)
        cell.imgURL = imgURLs![indexPath.item]
        
        // 重要 一定要记住,添加子控制器,否则响应者链条会被截断
        if !(childViewControllers as NSArray).containsObject(cell.viewerVC!) {
            // 添加子控制器
            addChildViewController(cell.viewerVC!)
        }
        
        return cell
    }
    private func rndColor() -> CGFloat {
        return CGFloat(arc4random_uniform(256)) / 255
    }
    
    // 隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

// 自定义UICollectionViewCell
class JPhotoBrowserCell : UICollectionViewCell {
    
    // 照片查看控制器
    lazy var viewerVC:JPhotoViewerVC? = {
        return JPhotoViewerVC()
    }()
    // 照片url 当为其赋值时,将值也赋给viewerVC的imgURL
    var imgURL : NSURL? {
        didSet {
            viewerVC?.imgURL = imgURL
        }
    }
    
    // 纯代码开发不走这个方法
    override func awakeFromNib() {
        JLog.i("\(__FUNCTION__)")
    }
    
    // 初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        JLog.i("\(__FUNCTION__) \(frame)",false)
        
        // 这里必须使用bounds 使用frame的话,水平滚动后,x改变会时图片位置不正确,虽然现在使用bounds同样有很多细节不行,但是比frame还是要好
        viewerVC?.view.frame = bounds
        // 将viewVC的view添加到自定义cell中
        self.addSubview(viewerVC!.view)
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

